//角色路由权限控制
import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css";
import { getToken } from "@/utils/cookie"; // progress bar style
import { Message } from "element-ui";

NProgress.configure({ showSpinner: false }); // NProgress configuration
const whiteList = ["/login", "/register", "/reset_password"]; // 不重定向白名单

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    //如果已经登录了
    if (to.path == "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      //已经有token
      let roles = store.getters.roles;
      if (!roles || roles.length === 0) {
        //拉取用户信息
        store
          .dispatch("GetUserInfo")
          .then(res => {
            console.log("roles", res.roles);
            // console.log("userInfo====", res);
            // const roles = res.roles.map(role => role.authority);
            const roles = res.roles;
            store.dispatch("GenerateRoutes", { roles }).then(() => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
              console.log("动态添加可访问路由表", store.getters.addRouters);
              next({ ...to, replace: true });
            });
          })
          .catch(err => {
            store.dispatch("FedLogOut").then(() => {
              Message.error(err || "登录信息已失效，请重新登录");
              next({ path: "/login" });
            });
          });
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
});
